package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.data.Page;
import com.dongdongshop.data.Result;
import com.dongdongshop.em.ResultEnum;
import com.dongdongshop.pojo.TbGoods;
import com.dongdongshop.pojo.TbItemCat;
import com.dongdongshop.service.GoodService;
import com.dongdongshop.service.ItemCatService;
import com.google.gson.Gson;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("good")
public class GoodsController {

    @Reference
    private GoodService goodService;

    @Reference
    private ItemCatService itemCatService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @RequestMapping("show")
    public String show(){
        return "admin/goods";
    }

    @RequestMapping("goodsList")
    @ResponseBody
    public Result goodsList(@RequestParam("goodsName") String goodsName, @RequestParam(defaultValue = "1")Integer pageNumber,@RequestParam(defaultValue = "5")Integer pageSize) {
        try {
            Page<TbGoods> goodList = goodService.goodsList(goodsName,pageNumber,pageSize);
            return Result.response(ResultEnum.SUCCESS).setData(goodList);
        } catch (Exception e) {
            return Result.response(ResultEnum.ERROR).setData(e);
        }
    }

    @RequestMapping("getItem")
    @ResponseBody
    public Result getItem(Long id){
        try {
            TbItemCat itemCat = itemCatService.updateById(id);
            return Result.response(ResultEnum.SUCCESS).setData(itemCat);
        } catch (Exception e) {
            return Result.response(ResultEnum.ERROR).setData(e);
        }
    }

    @RequestMapping("upStatus")
    @ResponseBody
    public Result upStatus(@RequestParam("ids[]")Long[] ids){

        try {

            Integer i = goodService.upStatus(ids);

            String s = new Gson().toJson(ids);
            rocketMQTemplate.convertAndSend("my-topic", s);
            return Result.response(ResultEnum.SUCCESS).setData(i);
        } catch (Exception e) {
            return Result.response(ResultEnum.ERROR).setData(e);
        }
    }

    @RequestMapping("outStatus")
    @ResponseBody
    public Result outStatus(@RequestParam("ids[]")Long[] ids){
        try {
            Integer i = goodService.outStatus(ids);
            return Result.response(ResultEnum.SUCCESS).setData(i);
        } catch (Exception e) {
            return Result.response(ResultEnum.ERROR).setData(e);
        }
    }
}
